//
//  MainWindow.swift
//  GitTFGUI
//
//  Created by Samuel Richard Magny on 2015-09-22.
//  Copyright © 2015 Samuel Richard Magny. All rights reserved.
//

import Cocoa
import TFSClient

class MainWindowController: NSWindowController {

    //Toolbar items
    @IBOutlet var commitToolbarItem: NSToolbarItem!
    @IBOutlet var checkinToolbarItem: NSToolbarItem!
    @IBOutlet var pullToolbarItem: NSToolbarItem!
    @IBOutlet var cloneToolbarItem: NSToolbarItem!
    @IBOutlet var cloneButtonFromToolbarItem: NSButton!
    
    //Status items
    @IBOutlet var progressIndicator: NSProgressIndicator!
    @IBOutlet var progressLabel: NSTextField!
    @IBOutlet var progressBarIcon: NSImageView!

    
    private let applicationModel:ApplicationModel
    private let tfsClient:ExtendedTFSClient
    private let externalCommitController:ExternalCommitController
    
    required init?(coder: NSCoder) {
        applicationModel = (NSApplication.sharedApplication().delegate as! AppDelegate).applicationModel
        
        tfsClient = applicationModel.tfsClient
        externalCommitController = applicationModel.externalCommitController
        
        super.init(coder:coder)
    }
    
    
    override func windowDidLoad() {
        super.windowDidLoad()
        progressIndicator.hidden = true
        
        let notificationCenter = applicationModel.notificationCenter
        notificationCenter.subscribe(self, selector: "workingDirectoryChanged:", identifier: TFSClientNotification.NotificationType.WorkingDirectoryChanged)
        notificationCenter.subscribe(self, selector: "showCommandProgress:", identifier: TFSClientNotification.NotificationType.ProgressInfo)
        
        setMainMenuActions(tfsClient.isCurrentWorkingDirectoryValid())
    }
    
    private func setMainMenuActions(isCurrentWorkingDirectoryValid:Bool)
    {
        let mainMenu = NSApplication.sharedApplication().mainMenu as! MainMenu
        let commandMenu = mainMenu.commandsMenu()
        
        let commitMenuItem = commandMenu.commitMenuItem()
        let pullMenuItem = commandMenu.pullMenuItem()
        let checkinMenuItem = commandMenu.checkinMenuItem()
        let cloneMenuItem = commandMenu.cloneMenuItem()
        let fetchMenuItem = commandMenu.fetchMenuItem()
        
        if(isCurrentWorkingDirectoryValid) {
            cloneMenuItem?.action = nil
            commitMenuItem?.action = Selector("commitButtonClicked:")
            pullMenuItem?.action = Selector("pullButtonClicked:")
            checkinMenuItem?.action = Selector("checkinButtonClicked:")
            fetchMenuItem?.action = Selector("fetchButtonClicked:")
        }
        else {
            cloneMenuItem?.action = Selector("cloneButtonClicked:")
            commitMenuItem?.action = nil
            pullMenuItem?.action = nil
            checkinMenuItem?.action = nil
            fetchMenuItem?.action = nil
        }
    }
    
    private func setToolbarItems(isCurrentWorkingDirectoryValid:Bool) {
        
        dispatch_async(dispatch_get_main_queue(), {
            self.commitToolbarItem.enabled = isCurrentWorkingDirectoryValid
            self.checkinToolbarItem.enabled = isCurrentWorkingDirectoryValid
            self.pullToolbarItem.enabled = isCurrentWorkingDirectoryValid
            
            if(isCurrentWorkingDirectoryValid)
            {
                self.cloneButtonFromToolbarItem.title = "Info"
            }
            else {
                self.cloneButtonFromToolbarItem.title = "Clone"
            }
        });
        
    }

    @IBAction func commitButtonClicked(sender: AnyObject) {
        
        if(!tfsClient.canCommit()) {
            return
        }
        
        
        if(externalCommitController.isInternalCommitEnabled()) {
            let viewController = self.storyboard!.instantiateControllerWithIdentifier(CommitViewController.storyboardId) as! CommitViewController
            viewController.tfsClient = self.tfsClient
            self.contentViewController!.presentViewControllerAsSheet(viewController)
        }
        else {
            externalCommitController.commit(tfsClient.workingDirectory, completionHandler: { (withSuccess) -> () in
                
            })
        }
        

    }
    
    @IBAction func checkinButtonClicked(sender: AnyObject) {
        tfsClient.checkin{ (withSuccess) -> () in
            
        }
        
        writeInfo("Checking in ...")
    }

    @IBAction func pullButtonClicked(sender: AnyObject) {
        tfsClient.pull { (withSuccess) -> () in
            
        }

        writeInfo("Pulling ...")
    }
    
    @IBAction func fetchButtonClicked(sender: AnyObject) {
        tfsClient.fetch { (withSuccess) -> () in
            
        }
        writeInfo("Fetching ...")
    }
    
    @IBAction func cloneButtonClicked(sender: AnyObject) {
        let viewController = self.storyboard!.instantiateControllerWithIdentifier(CloningViewController.storyboardId) as! CloningViewController
        viewController.tfsClient = self.tfsClient
        self.contentViewController!.presentViewControllerAsSheet(viewController)
    }
    

    override func prepareForSegue(segue: NSStoryboardSegue, sender: AnyObject?) {
        
        if var viewController = segue.destinationController as? TFSClientViewControllerProtocol
        {
            viewController.tfsClient = self.applicationModel.tfsClient
        }
        
    }
    
    //Notifications Implementation
    //****************************************************************
    dynamic private func showCommandProgress(notification: ProgressNotification)
    {
        writeInfo(notification.progressLocalizedString)
    }
    
    dynamic private func workingDirectoryChanged(notification: WorkingDirectoryChangedNotification)
    {
        setMainMenuActions(notification.isValid)
        setToolbarItems(notification.isValid)
    }
    
    dynamic private func commandDidStart(notification: NSNotification)
    {
        progressIndicator.hidden = false
        progressIndicator.startAnimation(self)
    }
    
    dynamic private func commandDidStop(notification: NSNotification)
    {
        progressIndicator.hidden = true
        progressIndicator.stopAnimation(self)
        writeInfo("")
    }

    
    
    
    //TFSClientDelegate Implementation
    //****************************************************************
    internal func tfsClientProgressUpdate(progressInfo: NSString) {
        writeInfo(progressInfo as String)
    }

    internal func tfsClientErrorOccured(reason: NSString)
    {
        dispatch_async(dispatch_get_main_queue(),{
            let alert = NSAlert()
            alert.addButtonWithTitle("Ok")
            alert.messageText = "Error"
            alert.informativeText = reason as String

            alert.runModal()
        })
    }
    //****************************************************************
    
   
    
    //Progress box
    //****************************************************************
    func writeInfo(progressInfo: String)
    {
        self.progressLabel.stringValue = progressInfo
        
        if(progressInfo.isEmpty) {
            progressBarIcon.hidden = false
        }
        else if(progressBarIcon.hidden == false) {
            progressBarIcon.hidden = true
        }
    }
    //****************************************************************

}
